﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Simple.Common.Data;
using Simple.Entity;
using Simple.Common.Core.Pager;
using Simple.ViewModel;
using Simple.Common.Pager;
using System.Data.Entity;
using Simple.Common.Core.Log;
using Simple.Common.EasyUICommon;
using EntityFramework.Extensions;
using Simple.Entity.Models;
using Simple.Entity.Enums;
using Simple.Services.Events;

namespace Simple.Service
{
    public class MenuService : ApplicationService
    {
        private readonly WorkEfRepository<Sys_Menu> _menuRepository;
        private readonly WorkEfRepository<Sys_RoleForMenu> _roleForMenuRepository;
        private readonly WorkEfRepository<Sys_UserForMenu> _sys_UserForMenuRepository;
        private readonly IEventPublisher _eventPublisher;

        public MenuService(WorkEfRepository<Sys_Menu> menuRepository, WorkEfRepository<Sys_RoleForMenu> roleForMenuRepository, WorkEfRepository<Sys_UserForMenu> sys_UserForMenuRepository, IEventPublisher eventPublisher)
        {
            _menuRepository = menuRepository;
            _roleForMenuRepository = roleForMenuRepository;
            _sys_UserForMenuRepository = sys_UserForMenuRepository;
            _eventPublisher = eventPublisher;
        }

        /// <summary>
        /// 查找菜单信息
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        public Sys_Menu FindById(long id)
        {
            return _menuRepository.Find(id);
        }

        /// <summary>
        /// 获取菜单列表信息
        /// </summary>
        /// <param name="queryModel"></param>
        /// <returns></returns>
        public List<MenuListModel> GetPageList(MenuQueryModel queryModel)
        {
            List<MenuListModel> model = _menuRepository.TableNoTracking.OrderBy(m => m.ParentId).ThenBy(m => m.Sort).Select(a => new MenuListModel
            {
                Id = a.Id,
                iconCls = a.Icon,
                ParentId = a.ParentId,
                Sort = a.Sort,
                CreateTime = a.CreateTime,
                MenuName = a.MenuName,
                MenuType = a.MenuType,
                ActionName = a.ActionName,
                ControllerName = a.ControllerName
            }).ToList();
            List<MenuListModel> reModel = new List<MenuListModel>();
            foreach (var item in model)
            {
                item.children = model.Where(m => m.ParentId == item.Id).ToList();
                if (item.ParentId == 0)
                {
                    reModel.Add(item);
                }
            }
            return reModel;
        }

        /// <summary>
        /// 根据菜单的父ID获取菜单类型【普通菜单，菜单按钮，菜单模块】
        /// </summary>
        /// <param name="parentId">父ID</param>
        /// <returns></returns>
        private MenuTypeEnum GetMenuTypeById(long parentId)
        {
            if (parentId <= 0)
            {
                return MenuTypeEnum.菜单模块;
            }
            else
            {
                var menuType = _menuRepository.TableNoTracking.First(m => m.Id == parentId).MenuType;
                if (menuType == MenuTypeEnum.菜单模块 || menuType == MenuTypeEnum.普通菜单)
                {
                    menuType++;
                }
                else
                {
                    menuType = MenuTypeEnum.菜单模块;
                }
                return menuType;
            }
        }

        /// <summary>
        /// 添加菜单模块
        /// </summary>
        /// <param name="modularDto">菜单模块对象</param>
        /// <returns></returns>
        public SimpleResult AddModular(Sys_Menu sys_Menu)
        {
            int count = _menuRepository.TableNoTracking.Count(m => m.MenuName == sys_Menu.MenuName && m.MenuType == MenuTypeEnum.菜单模块);
            if (count > 0)
            {
                return GetError("已经存在同名模块");
            }

            int ret = _menuRepository.Add(sys_Menu);
            if (ret > 0)
                _eventPublisher.EntityInserted<Sys_Menu>(sys_Menu);
            return GetResult(ret);
        }

        /// <summary>
        /// 添加菜单
        /// </summary>
        /// <param name="menuDto">菜单对象</param>
        /// <returns></returns>
        public SimpleResult AddMenu(Sys_Menu sys_Menu)
        {
            int count = _menuRepository.TableNoTracking.Count(m => m.MenuName == sys_Menu.MenuName && m.ParentId == sys_Menu.ParentId && m.MenuType == MenuTypeEnum.普通菜单);
            if (count > 0)
            {
                return GetError("已经存在同名菜单");
            }
            int ret = _menuRepository.Add(sys_Menu);
            if (ret > 0)
                _eventPublisher.EntityInserted<Sys_Menu>(sys_Menu);
            return GetResult(ret);
        }


        /// <summary>
        /// 新增菜单
        /// </summary>
        /// <param name="sys_Menu">菜单对象</param>
        /// <returns></returns>
        public SimpleResult AddButton(Sys_Menu sys_Menu)
        {
            int count = _menuRepository.TableNoTracking.Count(m => m.MenuName == sys_Menu.MenuName && m.ParentId == sys_Menu.ParentId);
            if (count > 0)
            {
                return GetError("已经存在同名按钮");
            }
            int ret = _menuRepository.Add(sys_Menu);
            return GetResult(ret);
        }

        /// <summary>
        /// 批量增加菜单，【用于刷新菜单界面功能】
        /// </summary>
        /// <param name="menuList">菜单列表</param>
        /// <returns></returns>
        public SimpleResult AddRange(List<Sys_Menu> menuList)
        {
            int ret = _menuRepository.AddRange(menuList);
            return GetResult(ret);
        }

        /// <summary>
        /// 修改菜单信息
        /// </summary>
        /// <param name="sys_Menu">菜单信息</param>
        /// <returns></returns>
        public SimpleResult Update(Sys_Menu sys_Menu)
        {
            int count = _menuRepository.TableNoTracking.Count(m => m.MenuName == sys_Menu.MenuName && m.ParentId == sys_Menu.ParentId && m.Id != sys_Menu.Id);
            if (count > 0)
            {
                return GetError("已经存在同名菜单");
            }

            int ret = _menuRepository.Update(sys_Menu);
            if (ret > 0 && sys_Menu.MenuType != MenuTypeEnum.菜单按钮)
                _eventPublisher.EntityUpdated<Sys_Menu>(sys_Menu);
            return GetResult(ret);
        }

        /// <summary>
        /// 根据主键删除菜单
        /// </summary>
        /// <param name="menuId">菜单主键</param>
        /// <returns></returns>
        public SimpleResult Delete(long menuId)
        {
            int count = _roleForMenuRepository.TableNoTracking.Count(m => m.MenuId == menuId);
            if (count > 0)
            {
                return GetError("已经存在关联角色信息，不能删除");
            }

            count = _sys_UserForMenuRepository.TableNoTracking.Count(m => m.MenuId == menuId);
            if (count > 0)
            {
                return GetError("已经存在关联用户信息，不能删除");
            }

            var delMenu = _menuRepository.Find(menuId);
            if (delMenu == null)
            {
                return GetError();
            }
            int ret = _menuRepository.Delete(delMenu);
            _menuRepository.TableNoTracking.Where(m => m.ParentId == delMenu.Id).Delete();
            if (ret > 0 && delMenu.MenuType != MenuTypeEnum.菜单按钮)
                _eventPublisher.EntityDeleted<Sys_Menu>(delMenu);
            return GetResult(ret);
        }
    }
}
